const app = getApp();
const utils = require("../../utils/util.js");
const ble = require("../../utils/ble.js");
const CRC = require("../../utils/crc8.js");

Page({
  data: {
    temperature: 0, // 温度
    actualPlateNum: '', // 实际车牌
    estimatePlateNum: '', // 预计车牌
    connected: false, // 连接状态
    useStatus: false, // 使用状态
    isBinding: false, // 绑定状态
    bleName: null,
    plateIdx: null
  },
  /**
   * 生命周期函数--监听页面加载
   */
  // onLoad: function () {
  //   this.initData()
  //   this.checkWxVersion()
  //   this.watchData()
  // },

  onShow: function (options) {
    // let changePalte = app.globalData.changePalte
    // if (changePalte) {
    ble.closeBluetoothAdapter()
    this.initData()
    this.watchData()
    this.checkWxVersion()
    // app.setGlobalData({
    //   changePalte: false
    // })
    // }
  },

  // 初始化数据
  initData() {
    let idx = app.globalData.plateIdx
    let plateList = app.globalData.plateList
    let estimatePlateNum = plateList[idx].alias + plateList[idx].plate
    let bleName = plateList[idx].eName + plateList[idx].plate
    let lockId = plateList[idx].lockId
    let connected = app.globalData.connected
    let useStatus = app.globalData.useStatus
    let name = app.globalData.name
    // utils.setStorage('estimatePlateNum', estimatePlateNum)
    // utils.setStorage('bleName', bleName)
    app.setGlobalData({
      bleName: bleName,
      // lockId: lockId,
      plateIdx: idx
    })
    this.setData({
      estimatePlateNum: estimatePlateNum,
      // bleName: bleName,
      actualPlateNum: name,
      lockId: lockId,
      isBinding: lockId && connected ? true : false,
      useStatus: useStatus
    })
  },

  // 监听 globalData
  watchData() {
    let that = this
    app.$watch('connected', (val, old) => {
      console.log('connected', val)
      that.setData({
        connected: val
      })
    })
    app.$watch('temperature', (val, old) => {
      that.setData({
        temperature: val
      })
    })
    app.$watch('lockId', (val, old) => {
      console.log('val', val)
      that.setData({
        isBinding: val ? true : false
      })
      app.setGlobalData({
        canBind: false
      })
      if (that.data.isBinding) {
        that.popup.hidePopup()
      }
    })
    app.$watch('isBinding', (val, old) => {
      that.setData({
        isBinding: val
      })
      if (that.data.isBinding) {
        that.popup.hidePopup()
      }
    })
    app.$watch('useStatus', (val, old) => {
      that.setData({
        useStatus: val
      })
    })
    app.$watch('binding', (val, old) => {
      if (val) {
        that.popup.showPopup('按下锁具的配置按钮进行绑定', 60)
      }
    })
    app.$watch('name', (val, old) => {
        that.setData({
          actualPlateNum: val
        })
      }),
      app.$watch('estimatePlateNum', (val, old) => {
        if (val) {
          that.setData({
            estimatePlateNum: val
          })
        }
      })
  },

  onReady: function () {
    //获得popup组件
    this.popup = this.selectComponent("#popup");
  },
  showPopup() {
    this.popup.showPopup('按下锁具的配置按钮进行绑定', 60)
  },

  // 检查wx版本是否支持蓝牙
  checkWxVersion() {
    var that = this;
    var log =
      "获取微信版本号:" +
      app.getWxVersion() +
      "\n" +
      "获取客户端系统:" +
      app.getPlatform() +
      "\n" +
      "系统版本:" +
      app.getSystem() +
      "\n";

    console.log(log)
    //获取当前设备平台以及微信版本
    if (
      app.getPlatform() == "android" &&
      utils.versionCompare("6.5.7", app.getWxVersion())
    ) {
      that.checkModal("当前微信版本过低，请更新至最新版本")
    } else if (
      app.getPlatform() == "android" &&
      utils.versionCompare("4.3.0", app.getSystem())
    ) {
      that.checkModal("当前系统版本过低，请更新至Android4.3以上版本")
    } else if (
      app.getPlatform() == "ios" &&
      utils.versionCompare("6.5.6", app.getWxVersion())
    ) {
      that.checkModal("当前微信版本过低，请更新至最新版本")
    } else {
      ble.startScan()
    }
  },

  checkModal(content) {
    wx.showModal({
      title: "提示",
      content: content,
      showCancel: false
    });
  },

  // 跳转车辆管理页面
  toManage: utils.debounce(function () {
    wx.navigateTo({
      url: "../manage2/manage"
    });
  }, 200),

  // 重新连接
  restartConn: utils.debounce(function () {
    ble.closeBluetoothAdapter()
    this.initData()
    this.checkWxVersion()
    this.watchData()
    // ble.startScan()
  }, 300),

  // 解除绑定
  etUnbind: utils.debounce(function () {
    let that = this
    wx.showModal({
      title: "提示",
      content: '确定要解除绑定吗?',
      success: function (res) {
        if (res.confirm) {
          app.globalData.plateList[app.globalData.plateIdx].lockId = null
          app.setGlobalData({
            lockId: null,
            temperature: 0
          })
        }
      }
    });
  }, 300),

  // 密码验证
  etBind: utils.debounce(function () {
    if (this.data.connected && this.data.useStatus === 1 && !app.globalData.canBind) {
      app.setGlobalData({
        canBind: true
      })
      let password = utils.decimal2Hex(app.globalData.plateList[app.globalData.plateIdx].password)
      let crc8 = CRC(`FA0D09${password}`)
      let orderStr = `FA0D09${password}${crc8}16`
      let order = utils.HexString2Bytes(orderStr)
      ble.writeBLECharacteristicValue(order)
      if (!app.globalData.plateList[app.globalData.plateIdx].lockId) {
        app.setGlobalData({
          binding: true
        })
      }
    }
  }, 300),

  // 开锁
  handleUnlock: utils.debounce(function () {
    if (this.data.connected && this.data.isBinding && this.data.useStatus === 1) {
      let lockId = app.globalData.plateList[app.globalData.plateIdx].lockId
      let crc8 = CRC(`FA1101${lockId}`)
      let orderStr = `FA1101${lockId}${crc8}16`
      console.log(orderStr)
      let order = utils.HexString2Bytes(orderStr)
      ble.writeBLECharacteristicValue(order)
    }
  }, 300),

  // 关锁
  handleLock: utils.debounce(function () {
    if (this.data.connected && this.data.isBinding && this.data.useStatus === 1) {
      let lockId = app.globalData.plateList[app.globalData.plateIdx].lockId
      let crc8 = CRC(`FA1102${lockId}`)
      let orderStr = `FA1102${lockId}${crc8}16`
      console.log(orderStr)
      let order = utils.HexString2Bytes(orderStr)
      ble.writeBLECharacteristicValue(order)
    }
  }, 300),

  // 尾灯
  handleTaillight: utils.debounce(function () {
    if (this.data.connected && this.data.isBinding && this.data.useStatus === 1) {

      let lockId = app.globalData.plateList[app.globalData.plateIdx].lockId
      let crc8 = CRC(`FA1103${lockId}`)
      let orderStr = `FA1103${lockId}${crc8}16`
      console.log(orderStr)
      let order = utils.HexString2Bytes(orderStr)
      ble.writeBLECharacteristicValue(order)
    }
  }, 300),
  // 开窗
  handleOpenWindow: utils.debounce(function () {
    if (this.data.connected && this.data.isBinding && this.data.useStatus === 1) {
      this.popup.showPopup('正在打开车窗', 8);

      let lockId = app.globalData.plateList[app.globalData.plateIdx].lockId
      let crc8 = CRC(`FA1104${lockId}`)
      let orderStr = `FA1104${lockId}${crc8}16`
      console.log(orderStr)
      let order = utils.HexString2Bytes(orderStr)
      ble.writeBLECharacteristicValue(order)
    }
  }, 300),

  // 关窗
  handleCloseWindow: utils.debounce(function () {
    if (this.data.connected && this.data.isBinding && this.data.useStatus === 1) {
      this.popup.showPopup('正在关闭车窗', 8);

      let lockId = app.globalData.plateList[app.globalData.plateIdx].lockId
      let crc8 = CRC(`FA1105${lockId}`)
      let orderStr = `FA1105${lockId}${crc8}16`
      console.log(orderStr)
      let order = utils.HexString2Bytes(orderStr)
      ble.writeBLECharacteristicValue(order)
    }
  }, 300),

  // 温度
  handleTemperature: utils.debounce(function () {
    if (this.data.connected && this.data.isBinding && this.data.useStatus === 1) {
      let lockId = app.globalData.plateList[app.globalData.plateIdx].lockId
      let crc8 = CRC(`FA1106${lockId}`)
      let orderStr = `FA1106${lockId}${crc8}16`
      let order = utils.HexString2Bytes(orderStr)
      ble.writeBLECharacteristicValue(order)
    }
  }, 300),

  // 帮助
  handleHelp: utils.debounce(function () {
    wx.navigateTo({
      url: "../help/help"
    });
  }, 300)
});